/**
 * Copyright phonemap.com
 *
 * Licensed under the phonemap.com License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.phonemap.com/licenses/LICENSE-1.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var oldPos = null;
var timezone = null;

/**
 * Do geolocation.
 */
function getlocation() {
	if (navigator.geolocation) {
		navigator.geolocation
				.getCurrentPosition(positionSuccess, positionError);
	} else {
		positionError(-1);
	}
}

/**
 * Position error.
 * @param err
 */
function positionError(err) {
	var msg = "";
	switch (err.code) {
		case err.UNKNOWN_ERROR:
			msg = "Unable to find your location";
			break;
		case err.PERMISSION_DENINED:
			msg = "Permission denied in finding your location";
			break;
		case err.POSITION_UNAVAILABLE:
			msg = "Your location is currently unknown";
			break;
		case err.BREAK:
			msg = "Attempt to find location took too long";
			break;
		default:
			msg = "You need to enable location on browser to continue...";
	}
//	document.getElementById('status').innerHTML = msg;
	console.log(msg);
}

/**
 * Position Success.
 * @param position
 */
function positionSuccess(position) {
	// Centre the map on the new location
	var coords = position.coords || position.coordinate || position;
	var latLng = new google.maps.LatLng(coords.latitude, coords.longitude);
	curpos = latLng;
	if (oldPos != null) {
		dist = distance(oldPos.lat(), oldPos.lng(), curpos.lat(), curpos.lng(), 'K');
		
		if (dist > 0,006) {
			updatePosition(curpos);
			oldPos = curpos;
		}
	}
	

}

/**
 * Updates Position.
 * @param user
 */
function updatePosition(curpos) {
	console.log('Updating user into system...');
	//load user account from cookie
	var userId = $.cookie('useraccount');
	if (userId != '' && userId != null) {
		
		var located_time = calculateTime(timezone);
		var urlString = '&id=' + userId + '&latitude='
				+ curpos.lat() + '&longitude=' + curpos.lng() + '&located_time='
				+ located_time;
		$.ajax({
			url : "/user?action=updateposition"+urlString,
			type : "POST",
			data: userId,
			success : function(data) {
				console.log('Successfully updated ' + curpos.toString());
				//oldPos = curpos;
			},
			error : function(resp) {
				console.log('UnSuccessfully updated ' + curpos.toString());
			}
		});
	} 
	

}


//var listener = setInterval(function(){getlocation()},5000);
